import {
  getUserId,
  setToken,
  setUserId,
  setUserName,
  setUserPass,
  setUserRoles,
  setUserStatus
} from '@/libs/auth'
import deepClone from '@/libs/deepClone'
import type { ActionContext } from 'vuex'
import { getUserRoles } from '@/libs/auth'
import router from '@/router'
import { RouteRecordRaw } from 'vue-router'
import asyncRouters from '@/router/asyncRouters'
import { RootState } from '.'
import { webLogin, webRegisterAndLogin, webWxScanLogin } from '@/api/login'
import { logout } from '@/libs/toolkit'
import { message } from '@/libs/global/antDesignVue'
import { setStorage } from '@/libs/localstoreage'
import { uSelectWebUserInfo } from '@/api/user'
import { clearSession } from '@/libs/sessionStorage'
import { clearStorage } from '@/libs/localstoreage'

export type LoginState = {
  roles: null | number[]
  userName: string | null
  userId: string | null
  token: string | null
  userFuns: any[]
  userInfo: User.Info | null
}

export type LoginContext = ActionContext<LoginState, RootState>

export const state: LoginState = {
  roles: null,
  userName: null,
  userId: null,
  token: null,
  userFuns: [],
  userInfo: null
}
export const getters = {
  GETROLES(state: LoginState) {
    return state.roles
  },
  GETUSERID(state: LoginState) {
    return state.userId
  },
  GETUSERNAME(state: LoginState) {
    return state.userName
  },
  GETTOKEN(state: LoginState) {
    return state.token
  },
  userFuns: (state: LoginState) => state.userFuns,
  userInfo: (state: LoginState) => state.userInfo
}
export const mutations = {
  SETUSERINFO_ROLES(state: LoginState, data: number[]) {
    state.roles = data
    setUserRoles(data)
  },
  SETUSERINFO_TOKEN(state: LoginState, data: string) {
    state.token = data
    setToken(data)
  },
  SETUSERINFO_USERNAME(state: LoginState, data: string) {
    state.userName = data
    setUserName(data)
  },
  SETUSERINFO_USERID(state: LoginState, data: string) {
    state.userId = data
    setUserId(data)
  },
  SETUSERINFO(state: LoginState, data: User.Info) {
    state.userInfo = data
  },
  CLEARUSERINFO(state: LoginState, data: string) {
    state.roles = null
    state.userName = null
    state.userId = null
    state.token = null
    state.userInfo = null
  }
}

export const actions = {
  LOGIN({ commit, dispatch }: LoginContext, data: { userName: string; userPass: string }) {



    return new Promise(async (rep, rej) => {
      if (!data.userName) {
        message.warning('请输入账号')
        return rej(false)
      }
      if (!data.userPass) {
        message.warning('请输入密码')
        return rej(false)
      }

      /**登录接口调用 */
      webLogin(data)
        .then(loginParam => {
          // 存储用户信息
          commit('SETUSERINFO_USERNAME', loginParam.data.userName)
          commit('SETUSERINFO_USERID', loginParam.data.userId)
          commit('SETUSERINFO_ROLES', [1])
          commit('SETUSERINFO', loginParam.data)

          // 用户状态
          setUserStatus({ login: true })

          // 存储token
          setStorage('token', loginParam.data.token)

          // 登录完成后加载路由
          console.log('根据权限开始获取页面路由')

          dispatch('GenerateRoutes')
            .then(res => {
              rep(true)
            })
            .catch(err => {
              console.log('路由信息加载失败', err)
              router.push('/login')
              rej(false)
            })
        })
        .catch(err => {
          message.error('登陆失败！')
          rej(false)
        })
    })
  },
  PHONELOGIN({ commit, dispatch }: LoginContext, data: { userPhone: string; verfiyCode: string }) {
    return new Promise((rep, rej) => {
      if (!data.userPhone) {
        message.warning('请输入手机号')

        return rej(false)
      }
      if (!data.verfiyCode) {
        message.warning('请输入验证码')
        return rej(false)
      }

      /**登录接口调用 */
      webRegisterAndLogin(data)
        .then(res => {
          // 存储用户信息
          commit('SETUSERINFO_USERNAME', res.data.userName)
          commit('SETUSERINFO_USERID', res.data.userId)
          commit('SETUSERINFO_ROLES', [1])
          commit('SETUSERINFO', res.data)

          // 存储密码
          setUserPass('')

          // 用户状态
          setUserStatus({ login: true })

          // 登录完成后加载路由
          console.log('根据权限开始获取页面路由')

          dispatch('GenerateRoutes')
            .then(res => {
              rep(true)
            })
            .catch(err => {
              console.log('路由信息加载失败', err)
              router.push('/login')
              rej(false)
            })
        })
        .catch(err => { })
    })
  },
  WXSCANLOGIN({ commit, dispatch }: LoginContext, data: { userName: string; userWeichatId: string }) {
    return new Promise(async (rep, rej) => {
      if (!data.userName || !data.userWeichatId) {
        message.warning('登录信息错误，请重新扫码')
        return rej(false)
      }

      /**登录接口调用 */
      const res = await webWxScanLogin(data).catch(err => {
        message.error('登陆失败！')
      })

      if (!res) return rej(false)

      // 存储用户信息
      commit('SETUSERINFO_USERNAME', res.data.userName)
      commit('SETUSERINFO_USERID', res.data.userId)
      commit('SETUSERINFO_ROLES', [1])
      commit('SETUSERINFO', res.data)

      // 存储密码
      setUserPass('')

      // 用户状态
      setUserStatus({ login: true })

      // 登录完成后加载路由
      console.log('根据权限开始获取页面路由')

      dispatch('GenerateRoutes')
        .then(res => {
          rep(true)
        })
        .catch(err => {
          console.log('路由信息加载失败,返回登录页', err)
          logout()
          rej(false)
        })
    })
  },

  LOGOUT({ commit, dispatch }: LoginContext) {
    logout()
  },
  /**获取用户信息*/
  GetUserInfo: ({
    state,
    commit,
    rootGetters,
    dispatch
  }: LoginContext): Promise<{ roles: number[] | null }> => {
    return new Promise((rep, rej) => {
      try {
        // 这里应该调用接口，来获取用户信息
        const userId = getUserId()
        if (userId) {
          uSelectWebUserInfo({ userId })
            .then(res => {
              const roles = getUserRoles()
              commit('SETUSERINFO_ROLES', roles)
              commit('SETUSERINFO_USERNAME', res.data.userName)
              commit('SETUSERINFO_USERID', res.data.userId)
              commit('SETUSERINFO', res.data)
              rep({ roles: roles })
            })
            .catch(err => {
              console.error('用户信息加载失败', err)
              dispatch('LOGOUT').then(res => {
                rej(false)
              })
            })
        } else {
          rej(false)
        }
      } catch (err) {
        console.error('getuserinfo error place check', err)
        rej(false)
      }
    })
  },
  /**筛选需要的路由 */
  GenerateRoutes: ({ commit, dispatch, rootState }: LoginContext) => {
    return new Promise<boolean>(async (resolve, reject) => {
      try {
        const routers = deepClone(asyncRouters)

        routers.map((data: RouteRecordRaw) => {
          router.addRoute(data.name || data.path.replace('/', '-').substring(1), data)
        })

        console.log('路由加载完成', router.getRoutes())

        resolve(true)
      } catch (err) {
        console.error('路由信息加载失败', err)
        dispatch('LOGOUT').then(res => {
          reject(false)
        })
      }
    })
  }
}
export default {
  namespaced: true, // 声明命名空间
  state,
  mutations,
  actions,
  getters
}
